package cn.hchaojie.web.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Before;
import org.junit.Test;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

public class DemoDruidDataSource {
	DruidDataSource ds = null;
	
	@Before
	public void init() throws IOException {
		// 数据源
		ds = new DruidDataSource();
//		ds.setUrl("jdbc:mysql://localhost:3306/sakila");
//		ds.setUsername("root");
//		ds.setPassword("root");
//		ds.setDriverClassName("com.mysql.jdbc.Driver");	
		
		InputStream is = getClass().getClassLoader().getResourceAsStream("druid.properties");
		Properties props = new Properties();
		props.load(is);
		
		ds.configFromPropety(props);
	}
	
	@Test
	public void testInsert() {
		try {
			// 获取连接
			DruidPooledConnection connection = ds.getConnection();
			
			// 发送sql语句
			PreparedStatement ps = connection.prepareStatement("insert into actor (first_name, last_name) values ('宝强', '王')");
			int result = ps.executeUpdate();
			System.out.println("result:" + result);
			// 遍历结果
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void testDelete() {
		try {
			// 获取连接
			DruidPooledConnection connection = ds.getConnection();
			
			// 发送sql语句
			PreparedStatement ps = connection.prepareStatement("delete from actor");
			int result = ps.executeUpdate();
			System.out.println("result:" + result);
			// 遍历结果
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
